#include "WorldModel.h"
#include <iostream>

WorldModel::WorldModel(double width, double height)
{
    m_width=width;
    m_height=height;
}

WorldModel::~WorldModel(){
    std::cout<<"Destruction WorldModel"<<std::endl;
    m_bodies.clear();
    for(int i=0;i<m_objects.size();++i){
        delete m_objects[i];
    }
    m_objects.clear();
}

std::vector<Perception*> WorldModel::computePerceptionsFor(AgentBody& a){
    std::vector<Perception*> perceptions;
    if (a.exist()) {
        double x = a.getX();
        double y = a.getY();
        std::vector<AgentBody*> agentsInTheWorld = getAgentBodies();
        std::vector<AbstractSituatedObject*> otherObjects = getSituatedObjects();
        for (int i = 0; i < agentsInTheWorld.size(); i++) {
            if (agentsInTheWorld[i]->exist()) {
                int distance = Vector2D(agentsInTheWorld[i]->getX() - x, agentsInTheWorld[i]->getY() - y).length();
                // distance de perception : 10
                if (distance < 10) perceptions.push_back(new Perception(*(agentsInTheWorld[i])));
            }
        }
        for (int i = 0; i < otherObjects.size(); i++) {
                int distance = Vector2D(otherObjects[i]->getX() - x, otherObjects[i]->getY() - y).length();
                // distance de perception : 10
                if (distance < 10) perceptions.push_back(new Perception(*(otherObjects[i])));
        }
    }
    return perceptions;
}

void WorldModel::applyInfluences(){
    //Création liste d'actions
    std::vector<Action> actions;
    for(int i=0; i<m_bodies.size();++i){
        //On récupère les influences
        Influence *influence = m_bodies[i]->getInfluence();
        if (influence != NULL){
            struct Action a;

            //Création des actions
            a.body = m_bodies[i];
            a.rotation = m_bodies[i]->computeRotation(influence->getAngularInfluence());
            a.translation = m_bodies[i]->computeTranslation(influence->getLinearInfluence());
            actions.push_back(a);

            //On supprime les influences une fois
            //récupérées
            m_bodies[i]->removeInfluence();
        }
    }


    //Parcours liste d'actions
    for(int i = 0; i<actions.size(); ++i){
        move(actions[i].body,actions[i].translation,actions[i].rotation);
        //Suppression des pointeurs sur vecteurs
        delete actions[i].translation;
    }
    actions.clear();
}

/*void WorldModel::applyInfluences(vector<Influence> influences){
    for(int i=0;i<influences.size();++i){
        AgentBody abody = influences[i].getEmitter().getBody();
        //computesteeringbehaviour

        //Collision detection
        //adapter les mouvements selon les autres agents
    }

    //on applique toutes les actions
}*/


